package vip.zhenzicheng.nettybasic.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.AllArgsConstructor;

import java.net.InetSocketAddress;

/**
 * 基于Netty的客户端
 *
 * @author zhenzicheng
 * @date 2022-06-06 20:19
 */
@AllArgsConstructor
public class EchoClient {

  private final int port;
  private final String host;

  public static void main(String[] args) throws InterruptedException {
    new EchoClient(9999, "127.0.0.1").start();
  }

  public void start() throws InterruptedException {
    // 线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try {
      Bootstrap bootStrap = new Bootstrap();
      bootStrap.group(group)
          .channel(NioSocketChannel.class)
          .remoteAddress(new InetSocketAddress(host, port)) // 指定服务器的ip和端口
          // 客户端的SocketChannel直接连接，不需要指定childHandler
          .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
              socketChannel.pipeline()
                  .addLast(new EchoClientHandler());
            }
          });
      // 异步连接服务器，阻塞直到连接完成
      ChannelFuture future = bootStrap.connect().sync();
      // 阻塞直到服务器的ServerChannel被关闭
      future.channel().closeFuture().sync();

    } finally {
      group.shutdownGracefully().sync();
    }
  }

}
